// import moment from 'moment'
// import Cookies from 'js-cookie'
// import layout from '@/components/layout'
// const bcrypt = require('bcryptjs') //引入bcryptjs库
import First from '@/views/first'
import $constant from '@/utils/open/constant'
import $validate from '@/utils/open/validate'
import store from '@/store'
import router from '@/router'
/**
 * 公用脚本方法类
 */
export default {
  /**
   * 常量引用
   */
  // static: $constant,
  /**
   * 加密
   * @returns {string}
   * oldPwd: $2a$10$My07QGXPUGaIrQGRph4SguKiEQqcLgbTByrj/J7NLbLH5wiPMGx8i
   * newPwd: $2a$10$EBvqTkx2apD3x/cSsfUCt./Hv/1Kpp94Y9nKVl.wXvqDVpaTJEi7q
   */
  encryptionFn(value) {
    var bcryptSalt = bcrypt.genSaltSync(10) // 定义密码加密的计算强度,默认10
    var hash = bcrypt.hashSync(value, bcryptSalt) // 把自己的密码(this.registerForm.passWord)带进去,变量hash就是加密后的密码
    return hash
  },
  /**
   * 获取uuid
   * @returns {string}
   */
  uuid() {
    return (this.S4() + this.S4() + '-' + this.S4() + '-' + this.S4() + '-' + this.S4() + '-' + this.S4() + this.S4() + this.S4())
  },
  S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  },
  /**
   * 复制对象公共属性的值
   * @param {Object} obj1 拷贝的对象
   * @param {Array} arr 被拷贝的数组对象
   */
  // debugger
  copyObjComVal(obj1, arr) {
    if ($validate.isNull(obj1) && $validate.isNull(arr)) {
      return obj1
    }
    // debugger
    for (let obj2 of arr) {
      obj2 = obj2 || {}
      if ($validate.isNull(obj2)) {
        continue
      }
      for (const key in obj1) {
        if (key && obj2.hasOwnProperty(key)) {
          obj1[key] = obj2[key]
        }
      }
    }

    return obj1
  },
  /**
   * 复制对象属性
   * @param {Object} obj1 拷贝的对象
   * @param {Array} arr 被拷贝的数组对象
   */
  copyObjVal(obj1, arr) {
    // debugger
    if ($validate.isNull(obj1) && $validate.isNull(arr)) {
      return obj1
    }
    // debugger
    for (let obj2 of arr) {
      obj2 = obj2 || {}
      if ($validate.isNull(obj2)) {
        continue
      }
      for (const key in obj2) {
        if (key && obj2.hasOwnProperty(key)) {
          obj1[key] = obj2[key]
        }
      }
    }

    return obj1
  },
  /**
   * 格式化时间
   * pattern
   * yyyy-MM-dd HH:mm:ss
   * @param datetime
   * @param pattern
   */
  format(datetime, pattern) {
    return moment(datetime).format(pattern)
  },
  formatRoutes(aMenu) { // 格式化路由
    const aRouter = []
    for (const oMenu of aMenu) {
      const {
        path,
        component,
        name,
        icon,
        level,
        id,
        children,
        meta
      } = oMenu

      let componentPath = ''
      if (meta.title !== 'First') {
        componentPath = component
      }

      const oRouter = {
        path: path,
        componentPath: componentPath, // test
        component(resolve) {
          let componentPath = ''
          if (component === 'First') {
            // require(['@/views/first'], resolve)
            return First
          } else {
            componentPath = component
          }
          require([`../${componentPath}`], resolve) // 这里的格式需要特别注意，经测试，'../'这个符号只能写在这里
        },
        level: level,
        id: id,
        name: name,
        meta: meta,
        icon: icon,
        children: $validate.isNull(children) ? [] : this.formatRoutes(children)
      }

      // console.log('2:', oRouter)
      aRouter.push(oRouter)
    }

    return aRouter
  },
  /**
   * 匹配路由
   * @params {Array} arr 数组
   * @params {String} name 路由name
   */
  findRouterItem(arr, name) {
    arr = arr || []
    let flag = false
    arr.some(item => {
      if (this.getType(item) === 'Array') {
        flag = this.findRouterItem(item, name)
        return flag
      } else if (item && item.children) {
        flag = this.findRouterItem(item.children, name)
        return flag
      } else if (item.name === name) {
        // this.curSelectMenu = item
        // store.dispatch('navTabs/updatecurSelectTab', item)
        store.commit('navTabs/addTab', { tab: item, name })
        flag = true
        return flag
      }
    })
    return flag
  },
  /**
   * 截取链接末尾参数
   */
  getUserLoginData() {
    // debugger
    // 截取链接末尾参数(保证每次打开浏览器只截取一遍)
    const isCutOutUrl = this.getKeyVal('user', 'isCutOutUrl', 'sessionStorage')
    let firstUrlParam = this.getKeyVal('user', 'firstUrlParam', 'sessionStorage')
    if ($validate.isNull(isCutOutUrl)) {
      firstUrlParam = this.getCurPathParam() || {}
      if (!firstUrlParam.access_token) {
        firstUrlParam.access_token = 'Bearer userLogin'
      } else {
        firstUrlParam.access_token = 'Bearer ' + firstUrlParam.access_token
      }
      // firstUrlParam.access_token = 'Bearer ' + firstUrlParam.access_token
      // debugger
      this.setKeyVal('user', 'isCutOutUrl', true, 'sessionStorage')
      this.setKeyVal('user', 'firstUrlParam', firstUrlParam, 'sessionStorage')
    }
    return firstUrlParam
  },
  /**
   * 对象转url str
   * 只支持一级obj
  */
  obj2Str(obj) {
    let str = ''
    // debugger
    for (let key in obj) {
      if (key && obj.hasOwnProperty(key)) {
        let val = obj[key]
        // if (this.checkChinese(val)) {
        val = encodeURIComponent(val)
        // }
        str += '&' + key + '=' + val
      }
    }
    str = '?' + str.substr(1)
    return str
  },
  /**
   * 获取链接末尾参数
   * @param {string}  num：1. hash
   */
  getCurPathParam(num) {
    // debugger
    const newObj = {}
    if (num === 1) {
      const url = location.hash// 获取链接 #/...? 后的字符串，并组合成 json 格式
      const reg = /#\/.*?\?/gi

      const res = url.match(reg)
      if (res && url.match(reg).length > 0) {
        let str = url.replace(reg, '')
        str = str.replace(/#\/$/, '')
        const strs = str.split('&')
        for (let i = 0; i < strs.length; i++) {
          newObj[strs[i].split('=')[0]] = (strs[i].split('=')[1])
        }
      }
    } else {
      let url = location.search// 获取链接 #/...? 后的字符串，并组合成 json 格式
      if (url) {
        url = url.substr(1)
        const obj = url.split('&')
        let arr = []
        for (const key of obj) {
          arr = key.split('=')
          newObj[arr[0]] = arr[1]
        }
      }
    }
    return newObj
  },
  /**
   * 写cookies 
   * @param {String} name 
   */
  setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
  },
  /**
   * 读取cookies 
   * @param {String} name 
   */
  getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    debugger
    if (arr = document.cookie.match(reg))
      return unescape(arr[2]);
    else
      return null;
  },
  /** 
   * 删除cookies 
   * @param {String} name 
   */
  delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = this.getCookie(name);
    // debugger
    if (cval != null)
      document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
  },
  /**
   * 清空用户账户数据
   * 退出，密码出错都会执行
   */
  clearAccountFn() {
    store.dispatch('user/LoginOut') // 清除相关数据 clean
    const sessionArr = ['firstUrlParam', 'isCutOutUrl', 'userInfo', 'addRouters'] // 需要清除的存储数据
    // debugger
    sessionArr.forEach(k => {
      if (k) {
        window.sessionStorage.removeItem(k)
      }
    })
    const localStorageArr = []
    localStorageArr.forEach(k => {
      if (k) {
        window.localStorage.removeItem(k)
      }
    })
    this.delCookie('AUTH-SESSION')
    this.delCookie('GATEWAY-SESSION')
    // store.dispatch('user/ClearPermissionsAll') // 清除权限数据
    // store.dispatch('sys/UpdateTimerChangeToken', null) // 清除定时刷新token 定时器
    // router.push({ name: 'Login' })
  },
  /**
   * 返回首页
   */
  goHomeFn() {
    router.push('/')
  },
  /**
   * 跳到登录页
   */
  goLoginFn() {
    // http://192.168.2.51:8012/?access_token=0b21d69a-41f8-44be-b296-de6e3749ce52
    // console.log('跳到登录页')
    history.pushState({}, '', '/')
    this.clearAccountFn() // 清空用户账户数据
    const redirect_url = window.location.href
    // debugger
    window.location.href =
      'http://192.168.1.229:6060/userlogin?redirect_url=' + redirect_url
  },
  /**
   * 设置 临时 缓存
   * @param key
   * @param value
   */
  setSession(key, value) {
    // debugger
    return new Promise((resolve, reject) => {
      try {
        window.sessionStorage.setItem(key, JSON.stringify(value))
        resolve()
      } catch (e) {
        console.error('setSession 错误')
        reject('setSession 错误')
      }
    })
  },
  /**
   * 获取 临时 缓存
   * @param key
   */
  getSession(key) {
    const item = window.sessionStorage.getItem(key)
    if ($validate.isNull(item)) {
      return ''
    }
    return JSON.parse(window.sessionStorage.getItem(key))
  },
  /**
   * 设置 永久 缓存
   * @param key
   * @param value
   */
  setLocalStorage(key, value) {
    // debugger
    return new Promise((resolve, reject) => {
      try {
        window.localStorage.setItem(key, JSON.stringify(value))
        resolve()
      } catch (e) {
        console.error('setSession 错误')
        reject('setSession 错误')
      }
    })
  },
  /**
   * 获取 永久 缓存
   * @param key
   */
  getLocalStorage(key) {
    const item = window.localStorage.getItem(key)
    if ($validate.isNull(item)) {
      return ''
    }
    return JSON.parse(window.localStorage.getItem(key))
  },
  /**
   * 获取 cookie
   * @param key
   */
  getCookie(key) {
    return Cookies.get(key)
  },
  /**
   * 设置 cookie
   * @param key
   */
  setCookie(key, val) {
    return Cookies.set(key, val)
  },
  /**
   * 删除 cookie
   * @param key
   */
  removeCookie(key) {
    return Cookies.set(key)
  },
  /**
   * 节流函数
   * @param {function} fn
   * @param {Number} interval
   */
  throttle(fn, interval = 300) {
    let canRun = true
    return function () {
      if (!canRun) return
      canRun = false
      setTimeout(() => {
        fn.apply(this, arguments)
        canRun = true
      }, interval)
    }
  },
  /**
   * 存储 store , sessionStorage
   * 注意传参格式
   * @param {String} module
   * @param {String} key
   * @param {String} val
   * @param {String} storeName 可不传 localStorage,sessionStorage
   */
  setKeyVal(module, key, val, storeName) {
    // debugger
    const fnName = module + '/Update' + key.substring(0, 1).toUpperCase() + key.substring(1)
    const type = $validate.judgeTypeOf(val)
    if (type !== 'String' && type !== 'Undefined' && type !== 'Null') {
      store.dispatch(fnName, val)
      if (storeName) {
        let val1 = this.deepCloneObj(val)
        val1 = JSON.stringify(val1)
        window[storeName].setItem(key, val1)
      }
    } else {
      if (storeName) {
        window[storeName].setItem(key, val)
      }

      try {
        if (val.match(/\{/)) { // 若匹配到{则说明是json字符
          val = JSON.parse(val)
        }
      } catch (e) {
        // dosome...
      } finally {
        if (type === 'String') {
          store.dispatch(fnName, val)
        }
      }
    }
  },
  /**
   * 获取 store,sessionStorage
   * @param {String} module 模块名字
   * @param {String} key state属性
   * @param {Boolean} storeName localStorage,sessionStorage
   */
  getKeyVal(module, key, storeName) {
    let val = store.state[module][key]
    // debugger
    if ($validate.isNull(val) && !$validate.isNull(storeName)) {
      val = window[storeName].getItem(key)
      if (!$validate.isNull(val)) {
        this.setKeyVal(module, key, val)

        const type = $validate.judgeTypeOf(val)
        if (type === 'String' && val.match(/\{/)) { // 若匹配到{则说明是json字符
          val = JSON.parse(val)
        }
      }
    }
    return val
  },
  /**
   * 对象，浅拷贝
   * @param {Object} obj
   */
  easyCloneObj(obj) {
    const newObj = {}
    for (const i in obj) {
      if (i && obj.hasOwnProperty(i)) {
        newObj[i] = obj[i]
      }
    }
    return newObj
  },
  /**
   * 对象，深拷贝
   * @param {Object} obj
   */
  deepCloneObj(data) {
    const type = this.getType(data)
    let obj
    if (type === 'array') {
      obj = []
    } else if (type === 'object') {
      obj = {}
    } else {
      return data
    }
    if (type === 'array') {
      for (let i = 0, len = data.length; i < len; i++) {
        obj.push(this.deepCloneObj(data[i]))
      }
    } else if (type === 'object') {
      for (const key in data) {
        if (data.hasOwnProperty(key)) {
          obj[key] = this.deepCloneObj(data[key])
        }
      }
    }
    return obj
  },
  /**
   * 获取对象属性类型
   * @param e
   * @returns {string}
   */
  getType(e) {
    if (e == null) {
      return ''
    }
    if (e.constructor === Array) {
      return 'array'
    } else if (e.constructor === Object) {
      return 'object'
    } else if (e.constructor === String) {
      return 'string'
    } else if (e.constructor === Number) {
      return 'number'
    } else if (e.constructor === Boolean) {
      return 'boolean'
    }
    return ''
  },
  /**
   * 获取dom元素style
   * @param dom
   * @param attr
   */
  getStyle(dom, attr) {
    // debugger
    if (dom.currentStyle) {
      return dom.currentStyle[attr];
    } else {
      return getComputedStyle(dom, null)[attr];
    };
  }
}

export function oneOf(value, validList) {
  for (let i = 0; i < validList.length; i++) {
    if (value === validList[i]) {
      return true
    }
  }
  return false
}
